package com.zwb.boot.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author 头发又黑又长
 * @Date 2022/7/19 20:35
 * @email zwb15083976291@163.com
 */
@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    @ExceptionHandler(value = {SQLIntegrityConstraintViolationException.class})
    public R exceptionHandler(SQLIntegrityConstraintViolationException e) {
        String error = e.getMessage();
        log.error(error);
        if (error.contains("Duplicate entry")) {
            return R.error(error.split(" ")[2] + " 已存在");
        }
        return R.error("操作失败");
    }

    ;

}
